<template>
  <div class="app-container">
    <div class="query-box">
      <el-button type="primary" plain icon="el-icon-circle-plus-outline" size="small" class="mr10" @click="handleAdd">
        新增
      </el-button>
      <el-input v-model="query.code" size="small" placeholder="编码" class="list-query-input"></el-input>
      <el-input v-model="query.name" size="small" placeholder="名字" class="list-query-input"></el-input>
      <el-select v-model="query.status" placeholder="状态" size="small" class="list-query-select">
        <el-option label="请选择" value="">请选择</el-option>
        <el-option v-for="item in Object.keys(enableStatus)" :key="enableStatus[item]" :value="item"
                   :label="enableStatus[item]"></el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">搜索</el-button>
    </div>

    <el-table v-loading="loading" :data="list" element-loading-text="Loading" border fit class="table">
      <el-table-column align="left" label="编码">
        <template slot-scope="scope">{{ scope.row.code }}</template>
      </el-table-column>
      <el-table-column label="名称">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value=1 :inactive-value=2 active-color="#409EFF" inactive-color="#B9B9B9" @change="changeStatus(scope.$index, scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="所属单位">
        <template slot-scope="scope">{{ scope.row.orgName }}</template>
      </el-table-column>
      <el-table-column label="所属系统">
        <template slot-scope="scope">{{ scope.row.systemName }}</template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">{{ scope.row.remark }}</template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="创建时间" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | datetimeFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="authorize(scope.row)">授权</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination background layout="total, prev, pager, next" :current-page="query.pageNo"
                     :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
    </div>

    <!-- 添加或修改角色对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入系角色编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色名称" prop="code">
              <el-input v-model="form.name" placeholder="请输入角色名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色状态" prop="type">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in Object.keys(enableStatus)" :label="item">{{enableStatus[item]}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属单位">
              <treeSelect
                v-model="form.orgId"
                :options="extData.org"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择所属单位"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属系统" prop="type">
            <el-select v-model="form.systemCode" placeholder="所属系统" @change="querySysName" style="display:block">
              <el-option v-for="item in Object.keys(extData.sys)" :key="extData.sys[item].code" :value="extData.sys[item].code" :label="extData.sys[item].name"></el-option>
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 授权对话框 -->
    <el-dialog :title="authTitle" :visible.sync="authOpen" width="500px" append-to-body>
      <el-form ref="form" :model="authForm" :rules="rules" label-width="80px">
        <el-form-item label="权限">
<!--          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>-->
<!--          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>-->
          <el-tree
            class="tree-border"
            :data="authOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAuthForm">确 定</el-button>
        <el-button @click="cancelAuth">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {list, sys, saveRole, updateRoleStatus, delRole, treeOrg, auths} from "@/api/api";
  import TreeSelect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "Role",
    components: { TreeSelect },
    data() {
      return {
        enableStatus: window.enableStatus,
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 权限表格树数据
        list: [],
        authOptions: [],
        defaultProps: {
          children: "children",
          label: "name"
        },
        pageTotal: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        authTitle: false,
        authOpen: false,
        authForm: {},
        query: {
          code: undefined,
          name: undefined,
          pageNo: 0,
          pageSize: 10
        },
        // 表单参数
        form: {},
        extData: {
          sys: [],
          org: []
        },
        // 表单校验
        rules: {
          name: [{required: true, message: "权限名称不能为空", trigger: "blur"}],
          code: [{required: true, message: "权限编码不能为空", trigger: "blur"}],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 转换数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      /** 查询权限列表 */
      getList() {
        this.loading = true;
        list(this.query).then(response => {
          this.list = response.data.records;
          this.loading = false;
        });
      },
      // 获取下拉框的name
      queryOrgName(e) {
        let sysAttr = this.extData.org.filter((item)=>{
          return item.code === e
        });
        this.form.orgName = sysAttr[0].name
      },
      // 获取下拉框的name
      querySysName(e) {
        let sysAttr = this.extData.sys.filter((item)=>{
          return item.code === e
        });
        this.form.systemName = sysAttr[0].name
      },
      // 触发搜索按钮
      handleSearch() {
        this.$set(this.query, 'pageNo', 0)
        this.list()
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          code: undefined,
          name: undefined,
        };
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        // 拿系统数据和单位数据
        if(this.extData.sys.length == 0) {
          sys().then(res => {
            this.extData.sys = res.data
          })
        }
        if(this.extData.org.length == 0) {
          treeOrg().then(res => {
            this.extData.org = res.data
          })
        }
        this.reset();
        this.open = true;
        this.form.status = "1";
        this.title = "添加角色";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.form = row;
        this.open = true;
        this.title = "修改角色【" + row.name + "】";
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            saveRole(this.form).then(response => {
              this.msgSuccess((this.form.id ? "编辑" : "新增") + "角色成功");
              this.open = false;
              this.getList();
            });
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除名称为【' + row.name + '】的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          delRole(row.code);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 提交授权按钮 */
      submitAuthForm() {
          if (this.authForm.roleId) {
            this.authForm.auths = this.getAuthAllCheckedKeys();
            updateRoleAuth(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
      },
      /** 授权按钮 */
      authorize(row) {
        // this.reset();
        this.authForm.roleId = row.id;
        this.authOpen = true;
        this.authTitle = "角色授权";
        auths("admin").then(response => {
          this.authOptions = response.data;
          this.loading = false;
        });
      },
      // 取消按钮
      cancelAuth() {
        this.authOpen = false;
      },
      // 所有权限节点数据
      getAuthAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      changeStatus(index, row) {
        updateRoleStatus(row.id, row.status == 1 ? "enable" : "disable").catch(res => {
          this.list[index].status = row.status == 1 ? 2 : 1
          this.list[index].statusName = enableStatus[status]
        });
      },
      // 分页导航
      handlePageChange(val) {
        this.$set(this.query, 'pageNo', val)
        this.getList()
      }
    }
  };
</script>
